
# -*- coding: UTF-8 -*- 
# python 3.8.10 脚本编码utf8,测试平台win7,win10 pyside6.1.0
# 配置文件更新日期：2023.9.13 本工具更新日期：2023.9.27
# 导包 pip install PySide6 pywin32 许可：https://www.pythonguis.com/faq/pyqt-vs-pyside/
from PySide6.QtWidgets import QApplication,QMainWindow,QFileDialog,QMessageBox
from Ui_untitled import Ui_MainWindow
from PySide6.QtGui import QIcon,QDesktopServices,QFont
from PySide6.QtCore import QThread, Signal
from pathlib import Path
import mylib,re,os,shutil,time,res_rc,PySide6.QtCore,zipfile

# 全局变量处理
CATGlobalEnvPath='' 
CATEnvfName=''
CATGlobalEnvfPath="没有找到全局环境文件,请检查Catia是否安装正确或者手动选择"#从注册表读取
CATInstallPath='' 
CATUserSettingPath=''
CATMsgCatalogPath=''
content=''
 #资源文件
# dir_setting = mylib.resource_path(os.path.join("res","CATEnv2019"))

#切换代码页为utf8
os.system("chcp 65001") #import os

class Worker(QThread):
    finished_signal = Signal(str)
    
    def __init__(self, flag1=0,flag2=0,flag3=0,flag2_1=0,spinboxValue=0):
        super().__init__()
        self.flag1 = flag1
        self.flag2 = flag2
        self.flag3 = flag3
        self.flag2_1 = flag2_1
        self.spinboxValue =spinboxValue

    def run(self):
        # 模拟长时间运行的任务
        
        global CATGlobalEnvfPath
        global CATGlobalEnvPath
        global CATInstallPath
        global CATUserSettingPath
        global CATEnvfName
        global content
        content='执行操作：\n'
        content+='---------------------------------------\n'
        if not Path(CATGlobalEnvfPath).exists():
            pass
        elif CATUserSettingPath =='':
            content='没有找到Catia安装目录，请确认Catia是否正确安装，或者手动选择对应的环境变量文件(.txt)'
            pass
        else:
            if self.flag1 ==1 :
                print('worker执行操作1')
                print("环境变量路径："+CATGlobalEnvfPath)
                print("正在备份当前环境变量文件。。")
                shutil.make_archive(CATGlobalEnvPath+"备份"+str(time.time()),'zip',root_dir=CATGlobalEnvPath)
                env_f=open(CATGlobalEnvfPath,mode="a")                            
                # env_f.write(self.ui.plainTextEdit.toPlainText())
                env_f.write(
                u"!------------------------------------\n"
    "!Text append by Catia Setting tool\n"
    "CNEXTBACKGROUND=yes\n"
    "CATNoStartDocument=no\n"
    "CNEXTSPLASHSCREEN=no \n"
    "CATLM_ODTS=1\n"
    "L_WILSON_LAN=1\n"
    "CGM_ROLLINGOFFSET=1 \n"
    "TAILLE_MEMOIRE_CHOISIE=1 \n"
    "SHOW_CST_CHILDREN=1  \n"
    "MM_NO_REPLACE=1 \n"
    "IRD_PRODUCTTOPART=1 \n"
    "MFG_MULTI_MP_APPLY=1 \n"
    "MFG_CATMFG_REMOVE_MOTION_TOOL_CHANGE=1\n"
    "KEEP_HIDDEN_ELEMENT=1 \n"
    "cleanV4Topology=1 \n"
    "CATMigrSolidMUV4AsPart=1 \n"
    "REPORT_BREP_INFO=1 \n"
    "V5V4SaveAsVolume=1  \n"
    "V5V4CleanTolerance=0.01 \n"
    "V5V4MaxSimplif=1 \n"
            )
                env_f.close #写入结束
                print("环境变量修改完毕")
                content+='1.追加快速启动环境变量参数\n'
                content+=' 备份当前本机环境文件完毕，文件名：'+CATEnvfName+'.txt\n'
                content+=' 追加快速启动变量参数至环境文件完毕\n\n'
                pass
            if self.flag2 ==1:
                print('worker执行操作2')
                if self.flag2_1==1: #如果✔运行Catia一次打钩
                    print('worker:Catia运行1次打钩')
                    # time.sleep(0.1)
                    mylib.run_demo_exe(CATInstallPath,self.spinboxValue)
                    # time.sleep(self.ui.spinBox.value())
                    copyUSettingFiles()
                    copyCATMsgCatalogFiles()
                    content+='2.覆盖Catia用户配置文件\n'
                    content+='  备份本机当前用户配置文件完毕\n'
                    content+='  启动Catia程序1次，并关闭成功\n'
                    content+='  覆盖用户配置文件完毕\n'
                else:
                    content+='2.覆盖Catia用户配置文件\n'
                    content+='  备份本机当前用户配置文件完毕\n'
                    content+='  覆盖用户配置文件完毕\n'
                    copyUSettingFiles()
                    copyCATMsgCatalogFiles()
                pass
            # if self.flag3 == 1:
            #     pass
            #     print('worker执行操作3')
            #     copyCATMsgCatalogFiles()
            #     content+='3.覆盖汉化文件\n'
            #     content+='  备份本机当前语言相关文件完毕\n'
            #     content+='  覆盖汉化文件完毕\n'
            
            
        self.finished_signal.emit("Task finished!")

# 方法
class myWindow(QMainWindow):
    def __init__(self):
        global CATGlobalEnvfPath
        global CATEnvfName
        super().__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)                                              

        # 版本信息Label yo->用作debug用，展示时隐藏
        # self.ui.label_5.hide()
         
        #lEdit 全局环境文件路径-------1
        self.ui.lineEdit.setText(CATGlobalEnvfPath)
        
        #btn 选择文件（全局环境变量文件）
        self.ui.pushButton.clicked.connect(self.pushButtonM0)
        
        #chbox 启用手动选择1-------1
        self.ui.checkBox.stateChanged.connect(self.checkBoxM0)
        
        
        #chbox 启用编辑
        # self.ui.checkBox_2.clicked.connect(self.checkBox_2M0)
        
        
        #lEdit 用户配置文件路径-------3
        self.ui.lineEdit_2.setText(CATUserSettingPath)

        #btn 选择目录（用户配置目录）
        self.ui.pushButton_2.clicked.connect(self.pushButton_2M0)

        #chbox 启用手动选择2
        self.ui.checkBox_3.stateChanged.connect(self.checkBox_3M0)

        
        #chbox 打开Catia一次后再覆盖配置文件-------3
        self.ui.checkBox_6.stateChanged.connect(self.checkBox_6M0)
        
        #btn 执行
        self.ui.pushButton_3.clicked.connect(self.pushButton_3M0)
        
        #btn 打开全局环境变量文件目录
        self.ui.pushButton_4.clicked.connect(self.pushButton_4M0)
        
        #btn 打开用户目配置文件目录
        self.ui.pushButton_5.clicked.connect(self.pushButton_5M0)
        
        #Label 请等待复制完毕
        self.ui.label_6.hide()
        
        #act 协议
        self.ui.action.triggered.connect(lambda:QDesktopServices.openUrl(PySide6.QtCore.QUrl('https://gitee.com/dvaloveu/catia_setting_tool/blob/master/LICENSE')))

        #act 帮助
        self.ui.action_3.triggered.connect(lambda:QDesktopServices.openUrl(PySide6.QtCore.QUrl('https://gitee.com/dvaloveu/catia_setting_tool/blob/master/README.md')))

        #act 恢复初始状态
        self.ui.action_2.triggered.connect(self.action_2M0)
        
        #act 打开备份文件目录
        self.ui.action_5.triggered.connect(self.action_5M0)
        # self.ui.actiondebug.triggered.connect(lambda:self.ui.label_5.show())
            
    # ---------------成员方法-------------------
    #chbox 启用手动选择1
    def checkBoxM0(self,state):
        print("chbox启用手动选择1 "+str(state))
        if state==0:
            self.ui.pushButton.setEnabled(False)
            self.ui.lineEdit.setEnabled(False)
        elif state==2:
            self.ui.pushButton.setEnabled(True)
            self.ui.lineEdit.setEnabled(True)
            
    #btn 选择文件（全局环境变量）
    def pushButtonM0(self):
        global CATGlobalEnvfPath
        global CATUserSettingPath
        global CATGlobalEnvPath
        global CATEnvfName  
        
        print("电极1次pushbtn0")
        grp=QFileDialog.getOpenFileName(self,r'选择Catia全局环境变量文件(txt)',CATGlobalEnvPath,r'环境变量文件(*.txt)')
        CATGlobalEnvfPath=grp[0]
        print ("选择的全局环境变量路径为："+grp[0])
        CATGlobalEnvPath=os.path.dirname(CATGlobalEnvfPath)
        CATEnvfName=os.path.basename(CATGlobalEnvfPath)
        self.ui.lineEdit.setText(CATGlobalEnvfPath)
        #重新显示用户配置目录路径
        getParas(CATGlobalEnvfPath)
        self.ui.lineEdit_2.setText(CATUserSettingPath)

    #chbox 启用编辑
    def checkBox_2M0(self,state):
        print("chbox启用编辑 "+str(state))
        if state==True:
            replay=QMessageBox.warning(self,'是否启用环境变量编辑','请确认熟悉掌握Catia环境变量格式，再启用环境变量编辑功能！',QMessageBox.StandardButton.Ok | 
                                    QMessageBox.StandardButton.Ok,QMessageBox.StandardButton.No)
            # QMessageBox().button(QMessageBox.StandardButton.Ok).setText('是')
            if replay == QMessageBox.StandardButton.Ok:
                self.ui.checkBox_2.setChecked(True)
                self.ui.plainTextEdit.setEnabled(True)
            elif replay == QMessageBox.StandardButton.No:
                self.ui.checkBox_2.setChecked(False)
                self.ui.plainTextEdit.setEnabled(False)
        elif state==False:
            self.ui.plainTextEdit.setEnabled(False)
            
    
    #btn 选择目录（打开用户配置文件目录）
    def pushButton_2M0(self):
        global CATUserSettingPath
        print("电极1次pushbtn2")
        path=QFileDialog.getExistingDirectory(self,r'选择Catia用户配置文件目录',CATUserSettingPath)
        print(path)
        print ("选择的用户配置文件目录为："+path)
        CATUserSettingPath=path
        #重新显示用户配置目录路径
        self.ui.lineEdit_2.setText(CATUserSettingPath)
        
    #chbox 启用手动选择2
    def checkBox_3M0(self,state):
        print("chbox启用手动选择2 "+str(state))
        if state==0:
            self.ui.pushButton_2.setEnabled(False)
            self.ui.lineEdit_2.setEnabled(False)
        elif state==2:
            self.ui.pushButton_2.setEnabled(True)
            self.ui.lineEdit_2.setEnabled(True)

    #chbox 打开Catia一次后再覆盖配置文件
    def checkBox_6M0(self,state):
        print("chbox打开Catia一次 "+str(state))
        if state==0:
            self.ui.spinBox.setEnabled(False)
            # self.ui.label_6.hide()
        elif state==2:
            self.ui.spinBox.setEnabled(True)
            # self.ui.label_6.show()
            print('修改Label6完毕')
    
    #act 本工具恢复初始
    def action_2M0(self):
        global CATGlobalEnvfPath
        global CATUserSettingPath

        #重新从注册表读取环境文件
        getGlobalEvnPath()
        self.ui.lineEdit.setText(CATGlobalEnvfPath)
        
        #重新从全局环境变量文件读取用户配置目录和Catia安装目录
        getParas(CATGlobalEnvfPath)
        self.ui.lineEdit_2.setText(CATUserSettingPath)
        
        #所有checkbox恢复初始状态
        self.ui.checkBox.setChecked(False)
        self.ui.checkBox_5.setChecked(True)
        self.ui.checkBox_4.setChecked(True)
        # self.ui.checkBox_2.setChecked(False)
        self.ui.checkBox_3.setChecked(False)
        self.ui.checkBox_6.setChecked(False)
        self.ui.checkBox_7.setChecked(True)
        
        #其他控件复初始可用/不可用状态
        self.ui.pushButton.setEnabled(False)
        self.ui.lineEdit.setEnabled(False)
        # self.ui.plainTextEdit.setEnabled(False)
        self.ui.lineEdit_2.setEnabled(False)
        self.ui.pushButton_2.setEnabled(False)
        self.ui.spinBox.setEnabled(False)
        self.ui.label_6.hide()
    
    #action 打开备份文件目录
    def action_5M0(self):
        global CATGlobalEnvPath
        global CATUserSettingPath
        global CATMsgCatalogPath
        os.chdir(CATGlobalEnvPath)
        os.chdir(os.path.pardir)
        os.startfile(os.getcwd())
        os.chdir(CATUserSettingPath)
        os.chdir(os.path.pardir)
        os.startfile(os.getcwd())
        os.chdir(CATMsgCatalogPath)
        # os.chdir(os.path.pardir)
        os.startfile(os.getcwd())
        
    #btn 执行
    def pushButton_3M0(self):
        global CATGlobalEnvfPath
        global CATGlobalEnvPath
        global CATInstallPath
        global CATUserSettingPath
        global CATEnvfName
        global content

        btnflag1=0
        btnflag2=0
        btnflag3=0
        btnflag2_1=0
        btnspinboxValue=0
        
        if CATUserSettingPath =='' or CATUserSettingPath =="没有找到Catia用户设置目录，请检查全局环境文件是否正确！"or CATGlobalEnvfPath==None or CATGlobalEnvfPath=="":
            content="没有找到Catia安装目录，请确认Catia是否正确安装，或者手动选择对应的环境变量文件(.txt)\n"
            pass
        else:
            self.ui.label_6.show()         
            self.ui.pushButton_3.setText("执行中")
            self.ui.pushButton_3.setEnabled(False)
        # print ('选择环境文件为：'+str(Path(CATGlobalEnvfPath).exists()))
        print ('点击了执行按钮，chBox1状态：'+str(self.ui.checkBox_5.isChecked()))
        print ('chBox2状态：'+str(self.ui.checkBox_4.isChecked()))
        # print (self.ui.plainTextEdit.toPlainText())
        #如果操作1打钩
        if self.ui.checkBox_5.isChecked(): 
            print('操作1打钩，执行操作1')
            btnflag1=1
        
        #如果操作2打钩
        if self.ui.checkBox_4.isChecked():
            print('操作2打钩，执行操作2')
            btnflag2=1
            
            if self.ui.checkBox_6.isChecked(): #如果✔运行Catia一次打钩
                print("执行btn：chebox6打钩，执行Catia一次")
                btnflag2_1=1
                btnspinboxValue =self.ui.spinBox.value()
            print (self.ui.spinBox.value())
            
        
        # if self.ui.checkBox_7.isChecked():
        #     print('操作3打钩，执行操作3')
        #     btnflag3=1
            
            

        
        if self.ui.checkBox_5.isChecked()==False and self.ui.checkBox_4.isChecked()==False and self.ui.checkBox_7.isChecked()==False:
            content+='---------------------------------------\n'
            content+='未执行任何操作\n'
            content+='---------------------------------------\n'
        
            
        self.worker = Worker(btnflag1,btnflag2,btnflag3,btnflag2_1,btnspinboxValue)    
        self.worker.finished_signal.connect(self.on_task_finished)
        self.worker.finished_signal.connect(lambda:self.worker.deleteLater())
        self.worker.start()
          
        
        
        
        
        
        
    #btn 打开全局环境变量文件目录
    def pushButton_4M0(self):
        global CATGlobalEnvPath
        os.startfile(CATGlobalEnvPath)
        
    #btn 打开用户目配置文件目录
    def pushButton_5M0(self):
        global CATUserSettingPath
        os.startfile(CATUserSettingPath)
    
    def on_task_finished(self, message):
        global content
                    
        self.ui.pushButton_3.setText("执行")
        self.ui.pushButton_3.setEnabled(True)
        self.ui.label_6.hide()
        
        # 弹出提示框
        content+='---------------------------------------\n'
        # content+='\n是否关闭本工具？'
        msgbox=QMessageBox()
        # self,'执行结果',content,QMessageBox.StandardButton.Ok | 
        #                             QMessageBox.StandardButton.No,QMessageBox.StandardButton.Ok
        msgbox.setWindowTitle('执行结果')
        msgbox.setWindowIcon(QIcon(':/img/favicon.ico'))
        msgbox.setText(content)
        msgbox.setStandardButtons(QMessageBox.StandardButton.Ok | 
                                    QMessageBox.StandardButton.No)
        btnYes=msgbox.button(QMessageBox.StandardButton.Ok)
        btnNo=msgbox.button(QMessageBox.StandardButton.No)
        btnYes.setText('关闭本工具')
        btnNo.setText('返回')
        msgbox.exec()
        if msgbox.clickedButton()==btnYes:
            print ('电极了按钮关闭程序')
            self.close()

        print(message)    
        
        
# 从注册表获取全局用户变量文件txt
def getGlobalEvnPath():
    global CATGlobalEnvPath
    global CATEnvfName
    global CATGlobalEnvfPath
    try:
        reg=mylib.get_Reg_key("SOFTWARE\Classes\CATIA.Part\shell\open\command","")
    except Exception as e:  
        print("找不到注册表信息，请检查Catia是否安装正确")
        print(e)
        
    else:
        EnvfName=re.search(r'(-env) (.*) (-direnv)', str(reg))
        EnvPath=re.search(r'(-direnv) "(.*?)"', str(reg))
        print(EnvfName)
        print(EnvfName.groups())
        print("全局环境变量文件名== "+EnvfName.groups()[1])
        print("全局环境变量路径== "+EnvPath.groups()[1])
        CATGlobalEnvPath=EnvPath.groups()[1]
        CATEnvfName=EnvfName.groups()[1]
        CATGlobalEnvfPath=CATGlobalEnvPath+r'\\'+CATEnvfName+r'.txt'
        print ("当前Catia全局环境储存目录为："+CATGlobalEnvfPath)
        print("请确认与本机Catia环境编辑器中【全局环境】字段是否一致，如果有误请联系管理员")
        
        
    
def getParas(EnvfPath): #获取用户配置文件保存目录，获取软件安装目录
    global CATGlobalEnvfPath
    global CATGlobalEnvPath
    global CATUserSettingPath
    global CATInstallPath
    global CATMsgCatalogPath
    
    CATUserSettingPath='没有找到相关目录，请手动选择或检查全局环境文件'
    CATInstallPath='没有找到相关目录，请手动选择或检查全局环境文件'
    CATMsgCatalogPath='没有找到相关目录，请手动选择或检查全局环境文件'
    
    CATGlobalEnvPath=os.path.dirname(CATGlobalEnvfPath)
    
    if os.path.exists(EnvfPath):
            env_f=open(EnvfPath,errors = 'ignore')
            flag=0
            for line in env_f:
                # print(line)
                if line.__contains__("CATUserSettingPath"): 
                    line = line.split("=")
                    # print(line)
                    if line[1].__contains__("CSIDL_APPDATA"):
                        path=line[1].replace("CSIDL_APPDATA",os.getenv("APPDATA"))
                        path=path.replace("\n","")
                        CATUserSettingPath=path  
                        print("用户配置文件存放路径为："+CATUserSettingPath) #打印CATUserSettingPath
                        flag=1
                    else:
                        path=line[1].replace("\n","")
                        CATUserSettingPath=path
                        print("用户配置文件存放路径为："+CATUserSettingPath)
                        flag=1                          
                elif line.__contains__("CATInstallPath"): 
                    line = line.split("=")
                    # print(line)
                    CATInstallPath=line[1].replace("\n","")+r"\code\bin\CATSTART.exe"
                    print("Catia启动文件路径为："+CATInstallPath) #打印CATUserSettingPath  
                    flag=1
                elif line.__contains__("CATMsgCatalogPath"):
                    line = line.split("=")
                    # print(line)
                    CATMsgCatalogPath=line[1].replace("\n","")
                    print("CATMsgCatalogPath存放汉化包的路径为："+CATMsgCatalogPath) #打印CATUserSettingPath  
                    flag=1
                    
            print ('flag=='+str(flag))
            if flag==0:
                CATUserSettingPath="没有找到Catia用户配置目录，请检查全局环境文件是否正确！"
                CATInstallPath='没有找到Catia安装路径，请检查全局环境文件是否正确！'   
                CATMsgCatalogPath='没有找到CATMsgCatalogPath目录，请检查全局环境文件是否正确！' 
                
#复制解压并覆盖用户配置文件                    
def copyUSettingFiles():
    global CATUserSettingPath 
    dir_setting = mylib.resource_path(Path("res").resolve()/"CATEnv2019")
    shutil.make_archive(CATUserSettingPath+"备份"+str(time.time()),'zip',root_dir=CATUserSettingPath+r'\\')
    print("备份当前配置文件完毕")
    print("复制推荐配置文件到用户配置文件目录")
    shutil.copytree(dir_setting, CATUserSettingPath, dirs_exist_ok=True) #py38开始支持dir_exsit_OK参数
    shutil.unpack_archive(CATUserSettingPath+"\CATEnv2019.zip",CATUserSettingPath)
    print("解压并覆盖配置文件完毕")
    
    #复制解压并覆盖汉化文件                    
def copyCATMsgCatalogFiles(): 
    global CATMsgCatalogPath
    dir_setting = mylib.resource_path(Path("res").resolve()/"Simp_Chi")
    # shutil.make_archive(CATMsgCatalogPath+r'\\Simplified_Chinese'+"备份"+str(time.time()),'zip',root_dir=CATMsgCatalogPath+'\Simplified_Chinese\CATIA.CATNls')
    with zipfile.ZipFile(CATMsgCatalogPath+'\Simplified_Chinese'+"备份"+str(time.time())+'.zip', 'w') as zipf:
        zipf.write(CATMsgCatalogPath+'\Simplified_Chinese\CATIA.CATNls', arcname='\Simplified_Chinese\CATIA.CATNls')
    with zipfile.ZipFile(CATMsgCatalogPath+'\msgcatalog'+"备份"+str(time.time())+'.zip', 'w') as zipf:
        zipf.write(CATMsgCatalogPath+'\CATIA.CATNls', arcname='CATIA.CATNls')
    
    print("备份当前Simplified_Chinese文件完毕")
    print("复制汉化文件到Simplified_Chinese目录")
    shutil.copytree(dir_setting, CATMsgCatalogPath, dirs_exist_ok=True) #py38开始支持dir_exsit_OK参数
    shutil.unpack_archive(CATMsgCatalogPath+"\Simplified_Chinese.zip",CATMsgCatalogPath)
    print("解压并覆盖汉化文件完毕")
    
    
if __name__=='__main__':
    getGlobalEvnPath()
    getParas(CATGlobalEnvfPath)
    app=QApplication([])
    # font = QFont("微软雅黑")
    # app.setFont(font)
    window=myWindow()
    window.show()
    app.exec()
    
    

# Ref
# pyqt https://www.bilibili.com/video/BV1c84y1N7iL/?p=32&vd_source=643b695bf443383aff3ac701bed9e53a
# 嵌入式打包 https://www.bilibili.com/video/BV1gd4y1y7F3/
# 请根据Catia启动时间调整等待秒数,\n确保Catia启动完毕后再执行关闭Catia操作。\n请等待Catia关闭成功,Catia关闭之前不要点击本工具！